<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="web安全,CSRF,跨站点请求伪造," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="CSRF(Cross-site request forgery跨站请求伪造，也被称成为“one click attack”或者session riding，通常缩写为CSRF或者XSRF，是一种对网站的恶意利用。
一、CSRF攻击原理CSRF攻击原理比较简单，如图1所示。其中Web A为存在CSRF漏洞的网站，Web B为攻击者构建的恶意网站，User C为Web A网站的合法用户。1)用户C打开">
<meta property="og:type" content="article">
<meta property="og:title" content="web安全（2）-- CSRF（跨站点请求伪造）">
<meta property="og:url" content="http://www.taneroom.cn/2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/index.html">
<meta property="og:site_name" content="TaneRoom">
<meta property="og:description" content="CSRF(Cross-site request forgery跨站请求伪造，也被称成为“one click attack”或者session riding，通常缩写为CSRF或者XSRF，是一种对网站的恶意利用。
一、CSRF攻击原理CSRF攻击原理比较简单，如图1所示。其中Web A为存在CSRF漏洞的网站，Web B为攻击者构建的恶意网站，User C为Web A网站的合法用户。1)用户C打开">
<meta property="og:image" content="http://www.taneroom.cn/images/2016/11/25/20161101094856095.png">
<meta property="og:updated_time" content="2016-11-25T06:28:13.520Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="web安全（2）-- CSRF（跨站点请求伪造）">
<meta name="twitter:description" content="CSRF(Cross-site request forgery跨站请求伪造，也被称成为“one click attack”或者session riding，通常缩写为CSRF或者XSRF，是一种对网站的恶意利用。
一、CSRF攻击原理CSRF攻击原理比较简单，如图1所示。其中Web A为存在CSRF漏洞的网站，Web B为攻击者构建的恶意网站，User C为Web A网站的合法用户。1)用户C打开">
<meta name="twitter:image" content="http://www.taneroom.cn/images/2016/11/25/20161101094856095.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.taneroom.cn/2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/"/>





  <title> web安全（2）-- CSRF（跨站点请求伪造） | TaneRoom </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?91ca0f0e00c720ad3b92033fd9766f4b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">TaneRoom</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">低调的码农</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://www.taneroom.cn/2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="TaneRoom">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/avatar.png">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="TaneRoom">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="TaneRoom" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                web安全（2）-- CSRF（跨站点请求伪造）
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2016-11-25T14:18:57+08:00">
                2016-11-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web安全/" itemprop="url" rel="index">
                    <span itemprop="name">web安全</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <a href="/2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/" class="leancloud_visitors" data-flag-title="web安全（2）-- CSRF（跨站点请求伪造）">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">阅读次数 </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>CSRF(Cross-site request forgery跨站请求伪造，也被称成为“one click attack”或者session riding，通常缩写为CSRF或者XSRF，是一种对网站的恶意利用。</p>
<h2 id="一、CSRF攻击原理"><a href="#一、CSRF攻击原理" class="headerlink" title="一、CSRF攻击原理"></a>一、CSRF攻击原理</h2><p>CSRF攻击原理比较简单，如图1所示。其中Web A为存在CSRF漏洞的网站，Web B为攻击者构建的恶意网站，User C为Web A网站的合法用户。<br><img src="http://www.taneroom.cn/images/2016/11/25/20161101094856095.png" alt="CSRF攻击原理" title="CSRF攻击原理"><br>1)用户C打开浏览器，访问受信任网站A，输入用户名和密码请求登录网站A;<br>2)在用户信息通过验证后，网站A产生Cookie信息并返回给浏览器，此时用户登录网站A成功，可以正常发送请求到网站A;<br>3)用户未退出网站A之前，在同一浏览器中，打开一个TAB页访问网站B;<br>4)网站B接收到用户请求后，返回一些攻击性代码，并发出一个请求要求访问第三方站点A;<br>5)浏览器在接收到这些攻击性代码后，根据网站B的请求，在用户不知情的情况下携带Cookie信息，向网站A发出请求。网站A并不知道该请求其实是由B发起的，所以会根据用户C的Cookie信息以C的权限处理该请求，导致来自网站B的恶意代码被执行。</p>
<h2 id="二、CSRF漏洞防御"><a href="#二、CSRF漏洞防御" class="headerlink" title="二、CSRF漏洞防御"></a>二、CSRF漏洞防御</h2><p>CSRF漏洞防御主要可以从三个层面进行，即服务端的防御、用户端的防御和安全设备的防御。</p>
<h3 id="1-服务端的防御"><a href="#1-服务端的防御" class="headerlink" title="1 服务端的防御"></a>1 服务端的防御</h3><h4 id="1-1-验证HTTP-Referer字段"><a href="#1-1-验证HTTP-Referer字段" class="headerlink" title="1.1 验证HTTP Referer字段"></a>1.1 验证HTTP Referer字段</h4><p>根据HTTP协议，在HTTP头中有一个字段叫Referer，它记录了该HTTP请求的来源地址。在通常情况下，访问一个安全受限页面的请求必须来自于同一个网站。比如某银行的转账是通过用户访问<a href="http://bank.test/test?page=10&amp;userID=101&amp;money=10000页面完成，用户必须先登录bank.test，然后通过点击页面上的按钮来触发转账事件。当用户提交请求时，该转账请求的Referer值就会是转账按钮所在页面的URL(本例中，通常是以bank" target="_blank" rel="external">http://bank.test/test?page=10&amp;userID=101&amp;money=10000页面完成，用户必须先登录bank.test，然后通过点击页面上的按钮来触发转账事件。当用户提交请求时，该转账请求的Referer值就会是转账按钮所在页面的URL(本例中，通常是以bank</a>. test域名开头的地址)。而如果攻击者要对银行网站实施CSRF攻击，他只能在自己的网站构造请求，当用户通过攻击者的网站发送请求到银行时，该请求的Referer是指向攻击者的网站。因此，要防御CSRF攻击，银行网站只需要对于每一个转账请求验证其Referer值，如果是以bank. test开头的域名，则说明该请求是来自银行网站自己的请求，是合法的。如果Referer是其他网站的话，就有可能是CSRF攻击，则拒绝该请求。</p>
<h4 id="1-2-在请求地址中添加token并验证"><a href="#1-2-在请求地址中添加token并验证" class="headerlink" title="1.2 在请求地址中添加token并验证"></a>1.2 在请求地址中添加token并验证</h4><p>CSRF攻击之所以能够成功，是因为攻击者可以伪造用户的请求，该请求中所有的用户验证信息都存在于Cookie中，因此攻击者可以在不知道这些验证信息的情况下直接利用用户自己的Cookie来通过安全验证。由此可知，抵御CSRF攻击的关键在于：在请求中放入攻击者所不能伪造的信息，并且该信息不存在于Cookie之中。鉴于此，系统开发者可以在HTTP请求中以参数的形式加入一个随机产生的token，并在服务器端建立一个拦截器来验证这个token，如果请求中没有token或者token内容不正确，则认为可能是CSRF攻击而拒绝该请求。</p>
<h4 id="1-3-在HTTP头中自定义属性并验证"><a href="#1-3-在HTTP头中自定义属性并验证" class="headerlink" title="1.3 在HTTP头中自定义属性并验证"></a>1.3 在HTTP头中自定义属性并验证</h4><p>自定义属性的方法也是使用token并进行验证，和前一种方法不同的是，这里并不是把token以参数的形式置于HTTP请求之中，而是把它放到HTTP头中自定义的属性里。通过XMLHttpRequest这个类，可以一次性给所有该类请求加上csrftoken这个HTTP头属性，并把token值放入其中。这样解决了前一种方法在请求中加入token的不便，同时，通过这个类请求的地址不会被记录到浏览器的地址栏，也不用担心token会通过Referer泄露到其他网站。</p>
<h3 id="2-其他防御方法"><a href="#2-其他防御方法" class="headerlink" title="2 其他防御方法"></a>2 其他防御方法</h3><p>2.1 CSRF攻击是有条件的，当用户访问恶意链接时，认证的cookie仍然有效，所以当用户关闭页面时要及时清除认证cookie，对支持TAB模式(新标签打开网页)的浏览器尤为重要。<br>2.2 尽量少用或不要用request()类变量，获取参数指定request.form()还是request. querystring ()，这样有利于阻止CSRF漏洞攻击，此方法只不能完全防御CSRF攻击，只是一定程度上增加了攻击的难度。<br>代码示例：<br>下文将以 Java 为例，对上述三种方法分别用代码进行示例。无论使用何种方法，在服务器端的拦截器必不可少，它将负责检查到来的请求是否符合要求，然后视结果而决定是否继续请求或者丢弃。在 Java 中，拦截器是由 Filter 来实现的。我们可以编写一个 Filter，并在 web.xml 中对其进行配置，使其对于访问所有需要 CSRF 保护的资源的请求进行拦截。<br>在 filter 中对请求的 Referer 验证代码如下<br>清单 1. 在 Filter 中验证 Referer<br><figure class="highlight lasso"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 从 HTTP 头中取得 Referer 值</span></div><div class="line"><span class="built_in">String</span> <span class="keyword">referer</span>=request.getHeader(<span class="string">"Referer"</span>);</div><div class="line"><span class="comment">// 判断 Referer 是否以 bank.example 开头</span></div><div class="line"><span class="keyword">if</span>((<span class="keyword">referer</span>!=<span class="built_in">null</span>) &amp;&amp;(<span class="keyword">referer</span>.trim().startsWith(“bank.example”)))&#123;</div><div class="line">    chain.doFilter(request, response);</div><div class="line">&#125;<span class="keyword">else</span>&#123;</div><div class="line">    request.getRequestDispatcher(“error.jsp”).forward(request,response);</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>以上代码先取得 Referer 值，然后进行判断，当其非空并以 bank.example 开头时，则继续请求，否则的话可能是 CSRF 攻击，转到 error.jsp 页面。<br>如果要进一步验证请求中的 token 值，代码如下<br>清单 2. 在 filter 中验证请求中的 token<br><figure class="highlight lasso"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">HttpServletRequest req = (HttpServletRequest)request;</div><div class="line">HttpSession s = req.getSession();</div><div class="line"><span class="comment">// 从 session 中得到 csrftoken 属性</span></div><div class="line"><span class="built_in">String</span> sToken = (<span class="built_in">String</span>)s.getAttribute(“csrftoken”);</div><div class="line"><span class="keyword">if</span>(sToken == <span class="built_in">null</span>)&#123;</div><div class="line">    <span class="comment">// 产生新的 token 放入 session 中</span></div><div class="line">    sToken = generateToken();</div><div class="line">    s.setAttribute(“csrftoken”,sToken);</div><div class="line">    chain.doFilter(request, response);</div><div class="line">&#125; <span class="keyword">else</span>&#123;</div><div class="line">    <span class="comment">// 从 HTTP 头中取得 csrftoken</span></div><div class="line">    <span class="built_in">String</span> xhrToken = req.getHeader(“csrftoken”);</div><div class="line">    <span class="comment">// 从请求参数中取得 csrftoken</span></div><div class="line">    <span class="built_in">String</span> pToken = req.getParameter(“csrftoken”);</div><div class="line">    <span class="keyword">if</span>(sToken != <span class="built_in">null</span> &amp;&amp; xhrToken != <span class="built_in">null</span> &amp;&amp; sToken.<span class="keyword">equals</span>(xhrToken))&#123;</div><div class="line">        chain.doFilter(request, response);</div><div class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(sToken != <span class="built_in">null</span> &amp;&amp; pToken != <span class="built_in">null</span> &amp;&amp; sToken.<span class="keyword">equals</span>(pToken))&#123;</div><div class="line">        chain.doFilter(request, response);</div><div class="line">    &#125;<span class="keyword">else</span>&#123;</div><div class="line">        request.getRequestDispatcher(“error.jsp”).forward(request,response);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>首先判断 session 中有没有 csrftoken，如果没有，则认为是第一次访问，session 是新建立的，这时生成一个新的 token，放于 session 之中，并继续执行请求。如果 session 中已经有 csrftoken，则说明用户已经与服务器之间建立了一个活跃的 session，这时要看这个请求中有没有同时附带这个 token，由于请求可能来自于常规的访问或是 XMLHttpRequest 异步访问，我们分别尝试从请求中获取 csrftoken 参数以及从 HTTP 头中获取 csrftoken 自定义属性并与 session 中的值进行比较，只要有一个地方带有有效 token，就判定请求合法，可以继续执行，否则就转到错误页面。生成 token 有很多种方法，任何的随机算法都可以使用，Java 的 UUID 类也是一个不错的选择。<br>除了在服务器端利用 filter 来验证 token 的值以外，我们还需要在客户端给每个请求附加上这个 token，这是利用 js 来给 html 中的链接和表单请求地址附加 csrftoken 代码，其中已定义 token 为全局变量，其值可以从 session 中得到。<br>清单 3. 在客户端对于请求附加 token<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">appendToken</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    updateForms();</div><div class="line">    updateTags();</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateForms</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="comment">// 得到页面中所有的 form 元素</span></div><div class="line">    <span class="keyword">var</span> forms = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'form'</span>);</div><div class="line">    <span class="keyword">for</span>(i=<span class="number">0</span>; i&lt;forms.length; i++) &#123;</div><div class="line">        <span class="keyword">var</span> url = forms[i].action;</div><div class="line">        <span class="comment">// 如果这个 form 的 action 值为空，则不附加 csrftoken</span></div><div class="line">        <span class="keyword">if</span>(url == <span class="literal">null</span> || url == <span class="string">""</span> ) <span class="keyword">continue</span>;</div><div class="line">        <span class="comment">// 动态生成 input 元素，加入到 form 之后</span></div><div class="line">        <span class="keyword">var</span> e = <span class="built_in">document</span>.createElement(<span class="string">"input"</span>);</div><div class="line">        e.name = <span class="string">"csrftoken"</span>;</div><div class="line">        e.value = token;</div><div class="line">        e.type=<span class="string">"hidden"</span>;</div><div class="line">        forms[i].appendChild(e);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateTags</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> all = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'a'</span>);</div><div class="line">    <span class="keyword">var</span> len = all.length;</div><div class="line">    <span class="comment">// 遍历所有 a 元素</span></div><div class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>; i&lt;len; i++) &#123;</div><div class="line">        <span class="keyword">var</span> e = all[i];</div><div class="line">        updateTag(e, <span class="string">'href'</span>, token);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateTag</span>(<span class="params">element, attr, token</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> location = element.getAttribute(attr);</div><div class="line">    <span class="keyword">if</span>(location != <span class="literal">null</span> &amp;&amp; location != <span class="string">''</span> <span class="string">''</span> ) &#123;</div><div class="line">        <span class="keyword">var</span> fragmentIndex = location.indexOf(<span class="string">'#'</span>);</div><div class="line">        <span class="keyword">var</span> fragment = <span class="literal">null</span>;</div><div class="line">        <span class="keyword">if</span>(fragmentIndex != <span class="number">-1</span>)&#123;</div><div class="line">            <span class="comment">//url 中含有只相当页的锚标记</span></div><div class="line">            fragment = location.substring(fragmentIndex);</div><div class="line">            location = location.substring(<span class="number">0</span>,fragmentIndex);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">var</span> index = location.indexOf(<span class="string">'?'</span>);</div><div class="line">        <span class="keyword">if</span>(index != <span class="number">-1</span>) &#123;</div><div class="line">            <span class="comment">//url 中已含有其他参数</span></div><div class="line">            location = location + <span class="string">'&amp;csrftoken='</span> + token;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="comment">//url 中没有其他参数</span></div><div class="line">            location = location + <span class="string">'?csrftoken='</span> + token;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">if</span>(fragment != <span class="literal">null</span>)&#123;</div><div class="line">            location += fragment;</div><div class="line">        &#125;</div><div class="line">        element.setAttribute(attr, location);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>在客户端 html 中，主要是有两个地方需要加上 token，一个是表单 form，另一个就是链接 a。这段代码首先遍历所有的 form，在 form 最后添加一隐藏字段，把 csrftoken 放入其中。然后，代码遍历所有的链接标记 a，在其 href 属性中加入 csrftoken 参数。注意对于 a.href 来说，可能该属性已经有参数，或者有锚标记。因此需要分情况讨论，以不同的格式把 csrftoken 加入其中。<br>如果你的网站使用 XMLHttpRequest，那么还需要在 HTTP 头中自定义 csrftoken 属性，利用 dojo.xhr 给 XMLHttpRequest 加上自定义属性代码如下：<br>清单 4. 在 HTTP 头中自定义属性<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> plainXhr = dojo.xhr;// 重写 dojo.xhr 方法</div><div class="line">dojo.xhr = function(<span class="keyword">method</span>,args,hasBody) &#123;</div><div class="line">// 确保 header 对象存在</div><div class="line">args.headers = args.header || &#123;&#125;;</div><div class="line">tokenValue = '&lt;%=request.getSession(<span class="literal">false</span>).getAttribute(<span class="string">"csrftoken"</span>)%&gt;';</div><div class="line">    <span class="keyword">var</span> token = dojo.getObject(<span class="string">"tokenValue"</span>);    // 把 csrftoken 属性放到头中</div><div class="line">    args.headers[<span class="string">"csrftoken"</span>] = (token) ? token : <span class="string">"  "</span>;</div><div class="line">    <span class="keyword">return</span> plainXhr(<span class="keyword">method</span>,args,hasBody);</div><div class="line">&#125;;</div></pre></td></tr></table></figure></p>
<p>这里改写了 dojo.xhr 的方法，首先确保 dojo.xhr 中存在 HTTP 头，然后在 args.headers 中添加 csrftoken 字段，并把 token 值从 session 里拿出放入字段中。</p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/images/donate/wechat.png" alt="TaneRoom wechat" style="width: 200px; max-width: 100%;"/>
    <div>请博主喝一杯咖啡！</div>
</div>


      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/web安全/" rel="tag"># web安全</a>
          
            <a href="/tags/CSRF/" rel="tag"># CSRF</a>
          
            <a href="/tags/跨站点请求伪造/" rel="tag"># 跨站点请求伪造</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/11/25/web安全（1）-XSS（跨站脚本攻击）/" rel="next" title="web安全（1）-- XSS（跨站脚本攻击）">
                <i class="fa fa-chevron-left"></i> web安全（1）-- XSS（跨站脚本攻击）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/11/25/web安全（3）-ClickJacking（点击劫持）/" rel="prev" title="web安全（3）-- ClickJacking（点击劫持）">
                web安全（3）-- ClickJacking（点击劫持） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <div class="ds-share flat" data-thread-key="2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/"
     data-title="web安全（2）-- CSRF（跨站点请求伪造）"
     data-content=""
     data-url="http://www.taneroom.cn/2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/">
  <div class="ds-share-inline">
    <ul  class="ds-share-icons-16">

      <li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
      <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
      <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
      <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
      <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>

    </ul>
    <div class="ds-share-icons-more">
    </div>
  </div>
</div>
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/"
           data-title="web安全（2）-- CSRF（跨站点请求伪造）" data-url="http://www.taneroom.cn/2016/11/25/web安全（2）-CSRF（跨站点请求伪造）/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="TaneRoom" />
          <p class="site-author-name" itemprop="name">TaneRoom</p>
          <p class="site-description motion-element" itemprop="description">低调的码农</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">11</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">2</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2711247437" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/tanzhen1991910" target="_blank" title="CSDN">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  CSDN
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、CSRF攻击原理"><span class="nav-number">1.</span> <span class="nav-text">一、CSRF攻击原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、CSRF漏洞防御"><span class="nav-number">2.</span> <span class="nav-text">二、CSRF漏洞防御</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-服务端的防御"><span class="nav-number">2.1.</span> <span class="nav-text">1 服务端的防御</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-验证HTTP-Referer字段"><span class="nav-number">2.1.1.</span> <span class="nav-text">1.1 验证HTTP Referer字段</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-在请求地址中添加token并验证"><span class="nav-number">2.1.2.</span> <span class="nav-text">1.2 在请求地址中添加token并验证</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-在HTTP头中自定义属性并验证"><span class="nav-number">2.1.3.</span> <span class="nav-text">1.3 在HTTP头中自定义属性并验证</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-其他防御方法"><span class="nav-number">2.2.</span> <span class="nav-text">2 其他防御方法</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">TaneRoom</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"taneroom"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  








  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("BnRa0PjEwPETnK8UggnNxrvQ-gzGzoHsz", "gTNTrFanjWAJhrkpXA6VDjbf");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  


</body>
</html>
